package com.atom.module.mvvm.extren

import android.view.MenuItem
import androidx.appcompat.widget.PopupMenu
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate


/**
 *
 */
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
 fun PopupMenu.dismisses()= callbackFlow<Unit> {
    checkMainThread()
    val listener = PopupMenu.OnDismissListener {
        trySend(Unit)
    }
    setOnDismissListener(listener)
    awaitClose { setOnDismissListener(null) }
}.conflate()

/**
 *
 */
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun PopupMenu.itemClicks() = callbackFlow<MenuItem> {
    checkMainThread()
    val listener = PopupMenu.OnMenuItemClickListener {
        trySend(it)
        true
    }
    setOnMenuItemClickListener(listener)
    awaitClose { setOnMenuItemClickListener(null) }
}.conflate()
